<?php
/**
 * singleton db class
 */
class db
{
    // db instance
    protected static $_db = null;

    // the connection instacne
    protected $_conn = null;

    // no clone
    private function __clone() {}

    // construct
    protected function __construct() {}

    // get db instance
    public static function getDb()
    {
        if (null === self::$_db) {
            self::$_db = new self();
        }
        return self::$_db;
    }

    // do connection
    public function connect()
    {
        global $dbConfig;
        $this->_conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS);
        if (!$this->_conn or !mysqli_select_db($this->_conn, DB_NAME)) {
            exit('db error');
        }
        $this->execute("SET NAMES 'utf8'");
    }

    // execute the query
    public function execute($sql, $store = false)
    {
        $result = array();
        if (!$this->_conn) {
            $this->connect();
        }
        $query = mysqli_query($this->_conn, $sql, $store ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT);
        if ($query) {
            while($row = @mysqli_fetch_assoc($query)) {
                $result[] = $row;
            }
        }
        return $result;
    }

}